﻿using HDF.Common;
using HDF.Windows.Tools.Other;
using System;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace HDF.Windows.Tools
{
    public partial class TaskbarTranslateForm : Form
    {
        public TaskbarTranslateForm()
        {
            InitializeComponent();

            var path = Application.StartupPath + "\\config";
            if (File.Exists(path))
            {
                var config = File.ReadAllLines(path);
                if ((config?.Length ?? 0) < 2)
                {
                    this.SetTextBox("程序配置错误");
                    return;
                }
                TranslateExtensions.BaiduAppId = config[0];
                TranslateExtensions.BaiduKey = config[1];
            }
            else
            {
                this.SetTextBox("请先配置API接口信息");
                return;
            }

            this.Height = Screen.PrimaryScreen.Bounds.Height - Screen.PrimaryScreen.WorkingArea.Height;



            timer = new Timer();
            timer.Interval = 5000;
            timer.Tick += (s, e) =>
            {
                //应用全屏时，不执行，例如全屏播放视频/游戏时，
                if (FullScreenDetector.IsAnyAppFullScreen())
                {
                    this.Visible = false;
                    return;
                }

                if (!this.Visible)
                    this.Visible = true;

                ForceTopMost(this);
                //这种方式会触发detail窗体OnDeactivate，抢夺焦点，winapi方式不会
                //this.TopMost = true;
            };

        }
        [DllImport("user32.dll")]
        static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);

        static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
        const UInt32 SWP_NOACTIVATE = 0x0010;
        const UInt32 SWP_SHOWWINDOW = 0x0040;

        public void ForceTopMost(Form form)
        {
            SetWindowPos(form.Handle, HWND_TOPMOST, form.Left, form.Top, form.Width, form.Height, SWP_NOACTIVATE | SWP_SHOWWINDOW);
        }



        Timer timer;
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            timer.Start();

            this.SetPos();
        }


        protected override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);
            timer.Stop();
        }


        void SetPos()
        {

            this.Location = new Point(200, Screen.PrimaryScreen.Bounds.Bottom - this.Height);


            var file = Application.StartupPath + "\\location-翻译工具-任务栏";
            if (File.Exists(file))
            {
                var data = File.ReadAllText(file);
                this.Left = Convert.ToInt32(data);
            }

        }

        protected override CreateParams CreateParams
        {
            get
            {
                //设置WS_EX_TOOLWINDOW可让窗体在alt+tab视图中隐藏
                const int WS_EX_TOOLWINDOW = 0x80; // 工具窗口的扩展样式
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= WS_EX_TOOLWINDOW; // 添加工具窗口样式
                return cp;
            }
        }

        Font bigfont = new Font("宋体", 24F, FontStyle.Regular, GraphicsUnit.Point, 134);
        Font smallfont = new Font("宋体", 12F, FontStyle.Regular, GraphicsUnit.Point, 134);

        Graphics graphics;

        public void SetTextBox(string msg)
        {
            graphics ??= Graphics.FromHwnd(this.Handle);
            var size = graphics.MeasureString(msg, bigfont);
            var showbig = size.Width < this.Width;


            try
            {
                if (showbig)
                    this.txt_Key.Font = bigfont;
                else
                    this.txt_Key.Font = smallfont;



                txt_Key.Text = msg;
            }
            catch (Exception ex)
            {
                txt_Key.Text = ex.Message;
            }
        }


















        private int lastTickCount;//防止api调用过快，
        protected override void WndProc(ref Message m)
        {
            if (m.Msg == 0x031D)//WM_CLIPBOARDUPDATE
            {
                var tick = Environment.TickCount;
                if (tick - this.lastTickCount >= 200)
                    OnClipboardUpdate();
                this.lastTickCount = tick;
                m.Result = IntPtr.Zero;
            }
            else if (m.Msg != 0xA3)
                base.WndProc(ref m);

            //this.SetDragPosition(ref m);
        }



        public void OnClipboardUpdate()
        {
            if (Clipboard.ContainsText())
            {
                var text = Clipboard.GetText();
                text = text.Trim();
                if (string.IsNullOrEmpty(text))
                    return;
                if (text.Length > 1000)
                    text = text.Substring(0, 1000);

                o_text = text;

                try
                {
                    new Task(() =>
                    {
                        var resstring = TranslateExtensions.BaiduTranslate(text);
                        var res = Newtonsoft.Json.JsonConvert.DeserializeObject<TranslateExtensions.BaiduTranslateApiResult>(resstring);


                        var str = "";

                        if (res == null)
                        {
                            text = "请求返回序列化：null";
                            str = "请求返回序列化：null";
                        }
                        else if (res.error_code != null)
                        {
                            text = "请求返回error_code：" + res.error_code;
                            str = "请求返回error_code：" + res.error_code;
                        }
                        else
                            str = string.Join(Environment.NewLine, res.trans_result.Select(r => r.dst));

                        t_text = str;

                        this.Invoke(new Action(() =>
                        {
                            this.SetTextBox(str);
                            detailform.SetText(o_text, t_text);
                        }));


                    }).Start();
                }
                catch (Exception ex)
                {
                    this.SetTextBox("又出Bug了！~(￣▽￣)~*" + ex.ToString());
                }
            }
        }

        private void txt_Key_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                var str = txt_Key.Text.Trim();
                if (string.IsNullOrEmpty(str))
                    return;

                Clipboard.SetText(str);
                e.Handled = true;
            }
            else if (e.KeyCode == Keys.Escape)
            {
                this.Visible = !this.Visible;
            }
        }


        private string o_text;
        private string t_text;


        private TranslateDetailForm detailform = new TranslateDetailForm();


        public void ShowDetail()
        {
            detailform ??= new TranslateDetailForm();
            detailform.SetText(o_text, t_text);
            detailform.Show();
            detailform.Activate();
        }

    }










    public class FullScreenDetector
    {
        // Win32 API 导入
        [DllImport("user32.dll")]
        private static extern IntPtr GetForegroundWindow();

        [DllImport("user32.dll")]
        private static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);

        [DllImport("user32.dll")]
        private static extern int GetWindowLong(IntPtr hWnd, int nIndex);

        private const int GWL_STYLE = -16;
        private const int WS_MAXIMIZE = 0x01000000;
        private const int WS_BORDER = 0x00800000;

        [StructLayout(LayoutKind.Sequential)]
        private struct RECT
        {
            public int Left;
            public int Top;
            public int Right;
            public int Bottom;
        }

        // 检测当前是否有窗口全屏
        public static bool IsAnyAppFullScreen()
        {
            IntPtr hWnd = GetForegroundWindow();
            if (hWnd == IntPtr.Zero)
                return false;

            // 检查窗口是否最大化且无边框（常见于游戏/视频播放器）
            int style = GetWindowLong(hWnd, GWL_STYLE);
            bool isMaximized = (style & WS_MAXIMIZE) != 0;
            bool isBorderless = (style & WS_BORDER) == 0;

            // 检查窗口是否覆盖整个屏幕
            GetWindowRect(hWnd, out RECT windowRect);
            Screen currentScreen = Screen.FromHandle(hWnd);
            Rectangle screenBounds = currentScreen.Bounds;

            bool coversEntireScreen =
                windowRect.Left <= screenBounds.Left &&
                windowRect.Top <= screenBounds.Top &&
                windowRect.Right >= screenBounds.Right &&
                windowRect.Bottom >= screenBounds.Bottom;

            return (isMaximized && isBorderless) || coversEntireScreen;
        }

    }
}
